﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;

namespace H2.NET.Web.Workflow.DwzCode
{
    public class BasePage : TaskPage
    {
        #region 列表分页变量
        [SessionType]
        public clsCommon clsCmm = new clsCommon();
        public int TotalItemCount;
        public int PageSize;
        public int PageNumber;

        public string OrderField
        {
            get { return AksRequest.GetFormString("OrderField"); }
        }

        public string OrderDir
        {
            get
            {
                if (!string.IsNullOrEmpty(OrderField))
                {
                    return AksRequest.GetFormString("OrderDir") == "asc" ? "desc" : "asc";
                }

                return "";
            }
        }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";

            if (string.IsNullOrEmpty(clsCmm.comm_username))
            {
                clsCmm = Session["clsCmm"] as clsCommon;
                clsCmm = clsCmm ?? new clsCommon();
            }

            //不验证登录的页面
            var noValidates = new string[] { "taskview.aspx" };
            var currentPage = Path.GetFileName(Request.Path).ToString();

            //如果是超时以及未登陆系统的情况
            if (!noValidates.Contains(currentPage) && !clsCmm.isLogin(User.Identity.Name, User.Identity.AuthenticationType))
            {
                var strUserName = Request.QueryString["UserName"];
                if (string.IsNullOrEmpty(strUserName) || Util.Decode(strUserName).IndexOf('/') == -1)
                {
                    //转入登陆界面
                    var returnUrl = ResolveUrl("~/logon.aspx");

                    var builder = new StringBuilder();
                    builder.Append("<script type=\"text/javascript\">");
                    if (Util.AppSettings("debug").Trim().ToUpper() == "YES")
                    {
                        builder.Append("try {");
                        builder.Append("alertMsg.warn(\"登录超时，请重新登录\", {okCall: function () { location.href = '" + returnUrl + "'; }});");
                        builder.Append("} catch(e) {");
                        builder.Append("alert(\"登录超时，请重新登录\"); location.href = '" + returnUrl + "';");
                        builder.Append("}");
                    }
                    else
                    {
                        builder.Append("location.href='systemerror.aspx?ex=' + escape('对不起，域验证失效')");
                    }
                    builder.Append("</script>");

                    Response.Write(builder.ToString());

                    Response.End();
                }
                else
                {
                    clsCmm.chkLogin(Util.Decode(strUserName));
                }
            }

            PageSize = GetPageSize();

            //base.OnInit(e);
        }

        #region 消息及页面跳转处理

        readonly ActionResult _actionResult = new ActionResult();


        public void ErrorMsg(string message)
        {
            WriteToClient(_actionResult.ErrorMsg(message, ""));
        }

        public void ErrorMsg(string message, string navTabId)
        {
            WriteToClient(_actionResult.ErrorMsg(message, navTabId));
        }

        public void SuccessMsg(string navTabId)
        {
            WriteToClient(_actionResult.SuccessMsg(navTabId));
        }

        public void SuccessMsg(string navTabId, string strMsg, bool showMsg)
        {
            WriteToClient(_actionResult.SuccessMsg(navTabId, strMsg, showMsg));
        }


        public void SuccessMsg()
        {
            WriteToClient(_actionResult.SuccessMsg());
        }

        public void SuccessMsg(string navTabId, string callbackType)
        {
            WriteToClient(_actionResult.SuccessMsg(navTabId, callbackType));
        }

        public void SuccessMsg(string navTabId, string callbackType, string forword)
        {
            WriteToClient(_actionResult.SuccessMsg(navTabId, callbackType, forword));
        }

        public void ShowMessage(string message)
        {
            WriteToClient(_actionResult.SuccessMsg(message, "", "", ""));
        }

        public void SuccessMsgByRel(string rel)
        {
            WriteToClient(_actionResult.SuccessMsgByRel(rel));
        }

        public void WriteToClient(string str, string contentType = "text/json")
        {
            try
            {
                Response.Clear();
                Response.ContentType = contentType;
                Response.Write(str);
                Response.End();
            }
            catch (Exception ex)
            {
                //不做处理
                Console.Write(ex.ToString());
            }
        }

        #endregion

        #region 获取分页大小
        public int GetPageSize()
        {
            int pageSize = 20;
            if (Request.Cookies["AKS_PAGE_SIZE"] != null)
            {
                int.TryParse(Request.Cookies["AKS_PAGE_SIZE"].Value, out pageSize);
            }
            if (AksRequest.GetFormInt("numPerPage") > 0)
            {
                pageSize = AksRequest.GetFormInt("numPerPage");
            }

            if (pageSize == 0) pageSize = 20;

            return pageSize;
        }
        #endregion

        public string GenerateApplicationNo()
        {
            return Util.GenerateSequence(((object[])TaskAPI["PrefixNo"])[0].ToString() + "-" + System.DateTime.Now.ToString("yyMM"), "", 4);
        }
        public string GenerateApplicationNo(TaskAPI taskApi)
        {
            return Util.GenerateSequence(((object[])taskApi["PrefixNo"])[0].ToString() + "-" + System.DateTime.Now.ToString("yyMM"), "", 4);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetCache(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return string.Empty;
            }
            if (Cache[key.Trim()] == null)
            {
                var caches = (t_Cache.id > 0).List<t_Cache>(Storage.Context1);
                foreach (var cache in caches)
                {
                    HttpContext.Current.Cache.Insert(cache.CacheKey, cache.CacheValue);
                }
            }

            return Cache[key.Trim()] == null ? key : Cache[key.Trim()].ToString();
        }

        public void JsTip(string message)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('" + message + "', 'info');", true);
        }

        public string FormatDateTime(object val, string format)
        {
            if (val == null) return "";
            return Utils.StrToDateTime(val.ToString()).ToString(format);
        }
    }
}